package com.gs.m_index

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.gs.common.BaseStateCallback
import com.gs.common.constant.StateCode

class IndexPersistent(context: Context) {

    private val indexModel by lazy { IndexModel.getInstance(context) }
    private val handler = Handler(Looper.getMainLooper())

    fun autoLogin(callback: OnDoAutoLoginStateCallback) {
        Thread{
            // 查询数据耗时操作
            indexModel.autoLogin{
                when (it) {
                    StateCode.STATE_LOADING -> {
                        handler.post {
                            callback.onAutoLoginLoading()
                        }
                    }
                    StateCode.STATE_SUCCESS -> {
                        handler.post {
                            callback.onAutoLoginSuccess()
                        }
                    }
                    StateCode.STATE_FAILED -> {
                        handler.post {
                            callback.onAutoLoginFailed()
                        }
                    }
                    StateCode.NETWORK_ERROR -> {
                        handler.post {
                            callback.onNetworkError()
                        }
                    }
                    StateCode.SERVER_ERROR -> {
                        handler.post {
                            callback.onServerError()
                        }
                    }
                    StateCode.UNKNOWN_ERROR -> {
                        handler.post {
                            callback.onUnknownError()
                        }
                    }
                }
            }
        }.start()
    }

    interface OnDoAutoLoginStateCallback: BaseStateCallback {
        fun onAutoLoginLoading(){}

        fun onAutoLoginSuccess()

        fun onAutoLoginFailed()
    }

    companion object{
        private var instance: IndexPersistent? = null

        fun getInstance(context: Context): IndexPersistent {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = IndexPersistent(context)
                    }
                }
            }
            return instance!!
        }
    }
}